﻿<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<c:set var="basePath" value="${pageContext.request.contextPath}"/>
<!DOCTYPE HTML>
<html lang="zh-cn">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>商品管理</title>
    <jsp:include page="/resources/inc/head.jsp" />
    <link href="${basePath}/resources/zheng-admin/plugins/zTree_v3/css/metroStyle/metroStyle.css" rel="stylesheet"/>
    <link href="${basePath}/resources/manage/css/product/product/index.css" rel="stylesheet"/>
    <link href="${basePath}/resources/zheng-admin/plugins/bootstrap_switch/css/bootstrap3/bootstrap-switch.css"
          rel="stylesheet"/>
</head>
<body>
<aside id="iframe_aside" class="sidebar1">
    <div class="zTreeDemoBackground left">
        <ul id="aside_tree" class="ztree"></ul>
    </div>
</aside>
<div id="main">
    <div id="toolbar">
        <shiro:hasPermission name="product:product:create">
            <a class="waves-effect waves-button" href="javascript:;"
               onclick="openPage('新增商品','${basePath}/manage/product/product/create',null,getChecked(),true,false)">
                <i class="zmdi zmdi-plus"></i>新增商品
            </a>
        </shiro:hasPermission>
        <%--   <shiro:hasPermission name="product:product:delete">
               <a class="waves-effect waves-button" href="javascript:;"
                  onclick="batchDelete('${basePath}/manage/product/product/delete')">
                   <i class="zmdi zmdi-close"></i>删除商品</a>
           </shiro:hasPermission>--%>
    </div>
    <table id="table"></table>
</div>
<jsp:include page="/resources/inc/footer.jsp" />
<script src="${basePath}/resources/zheng-admin/plugins/bootstrap_switch/js/bootstrap-switch.js"></script>
<script>
    var types = ${types};
    var query = {};
    var $table = $('#table');
    $(function () {
        // bootstrap table初始化
        $table.bootstrapTable({
            url: '${basePath}/manage/product/product/list',
            height: getHeight(),
            striped: true,//隔行变色
            search: true,
            showRefresh: true,
            showColumns: true,//是否显示 内容列下拉框
            minimumCountColumns: 2,//当列数小于此值时，将隐藏内容列下拉框
            clickToSelect: true,//设置true 将在点击行时，自动选择rediobox 和 checkbox
            detailView: true,//设置为 true 可以显示详细页面模式。
            detailFormatter: 'detailFormatter',//格式化详细页面模式的视图。
            pagination: true,//设置为 true 会在表格底部显示分页条
            paginationLoop: false,//设置为 true 启用分页条无限循环的功能。
            sidePagination: 'server',
            silentSort: false,//设置为 false 将在点击分页按钮时，自动记住排序项。仅在 sidePagination设置为 server时生效.
            smartDisplay: false,//True to display pagination or card view smartly.
            escape: true,//转义HTML字符串，替换 &, <, >, ", `, 和 ' 字符.
            searchOnEnterKey: true,//设置为 true时，按回车触发搜索方法，否则自动触发搜索方法
            idField: 'id',//指定主键列
            maintainSelected: true,//设置为 true 在点击分页按钮或搜索按钮时，将记住checkbox的选择项
            toolbar: '#toolbar',
            queryParamsType: "",
            onLoadSuccess: function () {
                $("[name='my-checkbox']").bootstrapSwitch({
                    size: "mini",
                    onColor: "primary",
                    offColor: "danger",
                    onText: "已上架",
                    offText: "未上架",
                    onSwitchChange: function (event, state) {
                        var productId = $(this).attr("productId");
                        $.ajax({
                            type: "post",
                            contentType: "application/json;charset=utf-8",
                            url: "${basePath}/manage/product/product/updateMarketable",
                            data: JSON.stringify({productId: productId, marketable: state}),
                            success: function (res) {
                                if (res.code == 1) {
                                    layer.msg("修改成功", {icon: 1, time: 2000});
                                } else {
                                    layer.msg(res.message, {icon: 5, time: 2000});
                                }
                            },
                            fail: function () {
                                layer.msg("修改失败！", {icon: 5});
                            }
                        })
                    }

                });
            },
            queryParams: function (params) {
                params.id = query.id;
                return params;
            }
            ,
            columns: [
                {field: 'ck', checkbox: true},
                {
                    title: '商品图片',
                    align: 'center',
                    formatter: 'imageFormatter',
                    events: 'actionEvents',
                    clickToSelect: false
                },
                {field: 'name', title: '商品名称', align: 'center'},
                {field: 'brandName', title: '商品品牌', align: 'center'},
                {field: 'ctime', title: '发布日期', align: 'center', formatter: 'timeFormatter'},
                {
                    title: '商品状态',
                    align: 'center',
                    formatter: 'marketableFormatter',
                    clickToSelect: false
                }, {
                    field: 'action',
                    title: '操作',
                    align: 'center',
                    formatter: 'actionFormatter',
                    events: 'actionEvents',
                    clickToSelect: false
                }
            ]
        })
        ;
        initZTree();
    });
    // 格式化操作按钮
    setPageLength("30%");
    setPageWidth("450px");
    var zNodes;
    var updateData = {
        title: "'编辑商品'",
        url: "'${basePath}/manage/product/product/update/'",
        id: ""
    };
    var deleteData = {
        url: "'${basePath}/manage/product/product/delete'",
        id: ""
    };
    // 格式化操作按钮
    function marketableFormatter(value, row, index) {
        var marketable = row.marketable;
        var id = row.id;
        if (marketable) {
            return '<div class="switch"> ' +
                    '<input type="checkbox" checked name="my-checkbox" productId="' + id + '"/> </div>'
        } else {
            return '<div class="switch"> ' +
                    '<input type="checkbox" name="my-checkbox" productId="' + id + '"/> </div>'
        }
    }
    function actionFormatter(value, row, index) {
        updateData.id = row.id;
        deleteData.id = row.id;
        var updateHtml = '<a class="update" href="javascript:;" ' +
                'onclick="editProduct(' + updateData.title + ',' + updateData.url + ',' + updateData.id + ')" ' +
                'data-toggle="tooltip" title="Edit"><i class="glyphicon glyphicon-edit"></i></a>';
        var deleteHtml = '<a class="delete" href="javascript:;"' +
                'onclick="deleteOne(' + deleteData.url + ',' + deleteData.id + ')" ' +
                ' data-toggle="tooltip" title="Remove"><i class="glyphicon glyphicon-remove"></i></a>';
        return updateHtml + "  ";
    }
    function detailFormatter(index, row) {
        var skus = "";
        //添加sku信息
        $.ajax({
            type: 'get',
            dateType: "JSON",
            async: false,
            url: '${basePath}/manage/product/sku/getSku?productId=' + row.id,
            success: function (res) {
                skus = createSkuUl(res, row);
            },
            error: function () {
            }
        });
        return skus;
    }
    function imageFormatter(value, row, index) {
        var images = row.image_path;
        var image = '';
        var imageFlag = false;
        if (typeof(images) != "undefined" && images.length > 0) {
            images = JSON.parse(images);
            for (var i = 0; i < images.length; i++) {
                if (images[i].length > 0) {
                    image = '<image src="' + images[i] + '" style="max-width: 60px;max-height: 60px;">';
                    imageFlag = true;
                    break;
                }
            }
        }
        if (!imageFlag) {
            image = '<image src="${basePath}/resources/manage/image/noImg.png" style="max-width: 60px;max-height: 60px;">';
        }
        return image;
    }
    function editProduct(title, url, id) {
        $.ajax({
            type: 'get',
            dateType: "JSON",
            url: '${basePath}/manage/product/sku/isMarketable?productId=' + id,
            success: function (res) {
                if (res.code == 0) {
                    layer.msg("请下架商品！", {icon: 5, time: 2000});
                } else {
                    openPage(title, url, id, null, true, false);
                }
            },
            error: function () {
                layer.msg("操作失败！", {icon: 5, time: 2000});
            }
        });
    }
    var createSkuUl = function (array, product) {
        var ul = '<ul class="sku-ul">';
        $(array).each(function (index, data) {
            var attributes = data.attributes;
            var imageFlag = false;
            var sku = data.sku;
            ul += '<li skuId="' + sku.id + '">';
            //找到图片
            var imageDiv = '<div class="sku-image"><div class="sku-image-div">';
            $(attributes).each(function (aIndex, attribute) {
                if (imageFlag) {
                    return false;
                }
                if (attribute.image) {
                    var images = JSON.parse(attribute.image);
                    for (var i = 0; i < images.length; i++) {
                        if (images[i].length > 0) {
                            imageDiv += '<image src="' + images[i] + '">';
                            imageFlag = true;
                            break;
                        }
                    }
                }
            });
            if (!imageFlag) {
                var images = JSON.parse(product.image_path);
                for (var i = 0; i < images.length; i++) {
                    if (images[i].length > 0) {
                        imageDiv += '<image src="' + images[i] + '">';
                        imageFlag = true;
                        break;
                    }
                }
            }
            if (!imageFlag) {
                imageDiv += '<image src="${basePath}/resources/manage/image/noImg.png">';
            }
            imageDiv += '</div></div>';
            //添加规格
            var attrStr = "";
            if (attributes.length < 1) {
                attrStr = "无";
            } else {
                $(attributes).each(function (aIndex, attribute) {
                    attrStr += attribute.attributeValue + ' ';
                });
            }
            var attrDiv = '<div title="' + attrStr + '">规格：' + attrStr + ' </div>';
            var price = String(sku.price);
            if (price.indexOf(".") < 0) {
                price += ".00";
            }
            ul += imageDiv;
            ul += '<div title="' + sku.name + '">名称：' + sku.name + ' </div>';
            ul += attrDiv;
            ul += '<div title="￥' + price + '">售价：￥' + price + ' </div>';
            ul += '<div title="' + sku.inventory + '">库存：' + sku.inventory + ' </div>';
            ul += '<div><button type="button" class="btn btn-primary btn-xs" onclick="editInventory(' + sku.id + ')">添加库存</button></div>'
            ul += '</li>';
        });
        ul += '</ul>';
        return ul;
    }
    function initZTree() {
        $.ajax({
            url: "${basePath}/manage/product/category/all",
            type: "GET",
            dataType: "JSON",
            async: false,
            success: function (res) {
                var list = res.data;
                var zNodes = [{id: 0, name: "顶级", open: true}];
                list.forEach(function (data, index, array) {
                    zNodes.push({id: data.id, pId: data.pid, name: data.name});
                });
                $.fn.zTree.init($("#aside_tree"), setting, zNodes);
            }
        });
    }
    var setting = {
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onClick: onClick
        }
    };
    function onClick(event, treeId, treeNode, clickFlag) {
        query.id = treeNode.id;
        $('#table').bootstrapTable('refresh', {query: query});
    }
    function getChecked() {
        var treeObj = $.fn.zTree.getZTreeObj("aside_tree");
        var nodes = treeObj.getSelectedNodes();
        if (nodes < 1) {
            return null;
        }
        return "categoryId=" + nodes[0].id;
    }
    function editInventory(id) {
        $.ajax({
            type: 'get',
            dateType: "JSON",
            url: '${basePath}/manage/product/sku/isMarketable?skuId=' + id,
            success: function (res) {
                if (res.code == 0) {
                    layer.msg("请下架商品！", {icon: 5, time: 2000});
                } else {
                    openPage("添加库存", "${basePath}/manage/product/sku/editInventory/", id, null, false, true);
                }
            },
            error: function () {
                layer.msg("操作失败！", {icon: 5, time: 2000});
            }
        });
    }
</script>
</body>
</html>